package hr.eon.server.dao.impl;

import hr.eon.server.dao.DatabaseDao;
import hr.eon.server.dao.model.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

/**
 * Implementation of DAO layer of Server application.
 * 
 * @author mjovanovic
 * @since 0.0.1
 */
@Repository
public class DatabaseDaoImpl implements DatabaseDao {

    private static final Logger LOGGER = Logger.getLogger( DatabaseDaoImpl.class );

    private SessionFactory sessionFactory;

    public void setSessionFactory( SessionFactory sessionFactory ) {
        this.sessionFactory = sessionFactory;
    }

    public User doLogin( String username, String password ) {
        Session session = sessionFactory.openSession();
        Transaction transaction = null;

        User user = null;
        try {
            transaction = session.beginTransaction();

            String hashedPassword = "P" + DigestUtils.shaHex( password );

            // @formatter:off
            user = (User) session.createCriteria( User.class )
                .add( Restrictions.eq( "username", username ) )
                .add( Restrictions.eq( "password", hashedPassword ) )
                .uniqueResult();
            // @formatter:on

            if ( user != null ) {
                user.generateSessionToken();
            }

            transaction.commit();
        }
        catch ( HibernateException he ) {
            transaction.rollback();
            LOGGER.error( "Hibernate exception: " + he.getMessage() );
        }
        finally {
            session.close();
        }

        return user;
    }
}
